package com.smart.community.work.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smart.community.commons.annotation.ApiLog;
import com.smart.community.commons.enums.ApiLogOperationType;
import com.smart.community.commons.result.Result;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.work.dto.StaffQueryDTO;
import com.smart.community.work.service.StaffService;
import com.smart.community.work.vo.StaffVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 员工管理控制器
 * 基于用户表和用户物业公司关联表实现员工管理
 * 
 * 严格按照《Java后端SpringBoot代码开发规范_重构版.md》Controller规范实现：
 * - 统一返回格式：使用Result统一包装返回结果
 * - 参数验证：使用@Valid注解进行参数验证
 * - 异常处理：使用统一的异常处理机制，异常往外抛
 * - 日志记录：记录关键操作日志，避免Controller层log.error
 * - 权限控制：使用SecurityUtils获取当前用户信息
 * - 完整注释：所有接口都有完整的Swagger文档注释
 * 
 * @author Wu.Liang
 * @since 2025-01-30
 * @version 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/work/staff")
@RequiredArgsConstructor
@Validated
@Tag(name = "员工管理", description = "员工管理相关接口")
public class StaffController {

    private final StaffService staffService;

    /**
     * 分页查询员工列表
     * 支持多物业公司ID数组参数
     */
    @GetMapping("/list")
    @Operation(summary = "分页查询员工列表", description = "分页查询员工列表，支持多物业公司ID数组参数")
    public Result<IPage<StaffVO>> selectStaffPage(
            @Parameter(description = "分页参数") Page<StaffVO> page, 
            @Parameter(description = "查询参数") @RequestParam Map<String, Object> params) throws Exception {
        log.info("开始分页查询员工列表，当前页：{}，每页大小：{}，查询参数：{}", page.getCurrent(), page.getSize(), params);
        
        // 获取当前用户ID
        Long currentUserId = SecurityUtils.getCurrentUserId();
        log.info("当前用户ID：{}", currentUserId);
        
        // 构建查询DTO
        StaffQueryDTO queryDTO = new StaffQueryDTO();
        queryDTO.setPageNum((int) page.getCurrent());
        queryDTO.setPageSize((int) page.getSize());
        
        // 处理查询参数
        if (params.containsKey("keyword")) {
            queryDTO.setKeyword((String) params.get("keyword"));
        }
        if (params.containsKey("status")) {
            queryDTO.setStatus((Integer) params.get("status"));
        }
        if (params.containsKey("propertyCompanyIds")) {
            String propertyCompanyIdsStr = (String) params.get("propertyCompanyIds");
            if (propertyCompanyIdsStr != null && !propertyCompanyIdsStr.trim().isEmpty()) {
                String[] ids = propertyCompanyIdsStr.split(",");
                Long[] propertyCompanyIds = new Long[ids.length];
                for (int i = 0; i < ids.length; i++) {
                    propertyCompanyIds[i] = Long.parseLong(ids[i].trim());
                }
                queryDTO.setPropertyCompanyIds(propertyCompanyIds);
            }
        }
        
        IPage<StaffVO> result = staffService.selectStaffPage(page, queryDTO, currentUserId);
        log.info("分页查询员工列表成功，返回记录数：{}", result.getRecords().size());
        return Result.success("查询成功", result);
    }

    /**
     * 根据ID查询员工详情
     */
    @GetMapping("/{staffId}")
    @Operation(summary = "根据ID查询员工详情", description = "根据员工ID和物业公司ID查询员工详细信息")
    public Result<StaffVO> getStaffById(
            @Parameter(description = "员工ID") @PathVariable @NotNull Long staffId,
            @Parameter(description = "物业公司ID") @RequestParam(required = false) Long propertyCompanyId) throws Exception {
        log.info("查询员工详情，员工ID：{}，物业公司ID：{}", staffId, propertyCompanyId);
        
        Long currentUserId = SecurityUtils.getCurrentUserId();
        StaffVO staff = staffService.getStaffById(staffId, propertyCompanyId, currentUserId);
        
        if (staff == null) {
            return Result.fail("员工不存在或无权限查看");
        }
        
        return Result.success("查询成功", staff);
    }

    /**
     * 添加员工
     */
    @ApiLog(
        logTitle = "添加员工",
        logType = 2,
        moduleName = "工作管理",
        operationType = ApiLogOperationType.ADD
    )
    @PostMapping
    @Operation(summary = "添加员工", description = "添加新员工")
    public Result<Long> addStaff(
            @Parameter(description = "员工信息") @RequestBody @Valid StaffQueryDTO staffDTO) throws Exception {
        log.info("添加员工，员工信息：{}", staffDTO);
        
        Long currentUserId = SecurityUtils.getCurrentUserId();
        Long staffId = staffService.addStaff(staffDTO, currentUserId);
        
        return Result.success("添加成功", staffId);
    }

    /**
     * 更新员工信息
     */
    @ApiLog(
        logTitle = "更新员工信息",
        logType = 2,
        moduleName = "工作管理",
        operationType = ApiLogOperationType.UPDATE
    )
    @PutMapping("/{staffId}")
    @Operation(summary = "更新员工信息", description = "更新员工信息")
    public Result<Void> updateStaff(
            @Parameter(description = "员工ID") @PathVariable @NotNull Long staffId,
            @Parameter(description = "员工信息") @RequestBody @Valid StaffQueryDTO staffDTO) throws Exception {
        log.info("更新员工信息，员工ID：{}，员工信息：{}", staffId, staffDTO);
        
        Long currentUserId = SecurityUtils.getCurrentUserId();
        staffService.updateStaff(staffId, staffDTO, currentUserId);
        
        return Result.success();
    }

    /**
     * 删除员工
     */
    @ApiLog(
        logTitle = "删除员工",
        logType = 2,
        moduleName = "工作管理",
        operationType = ApiLogOperationType.DELETE
    )
    @DeleteMapping("/{staffId}")
    @Operation(summary = "删除员工", description = "删除员工")
    public Result<Void> deleteStaff(
            @Parameter(description = "员工ID") @PathVariable @NotNull Long staffId) throws Exception {
        log.info("删除员工，员工ID：{}", staffId);
        
        Long currentUserId = SecurityUtils.getCurrentUserId();
        staffService.deleteStaff(staffId, currentUserId);
        
        return Result.success();
    }

    /**
     * 更新员工状态
     */
    @ApiLog(
        logTitle = "更新员工状态",
        logType = 2,
        moduleName = "工作管理",
        operationType = ApiLogOperationType.UPDATE
    )
    @PutMapping("/{staffId}/status")
    @Operation(summary = "更新员工状态", description = "更新员工状态")
    public Result<Void> updateStaffStatus(
            @Parameter(description = "员工ID") @PathVariable @NotNull Long staffId,
            @Parameter(description = "状态") @RequestParam @NotNull Integer status) throws Exception {
        log.info("更新员工状态，员工ID：{}，状态：{}", staffId, status);
        
        Long currentUserId = SecurityUtils.getCurrentUserId();
        staffService.updateStaffStatus(staffId, status, currentUserId);
        
        return Result.success();
    }

    /**
     * 搜索员工
     */
    @GetMapping("/search")
    @Operation(summary = "搜索员工", description = "根据关键词和状态搜索员工")
    public Result<List<StaffVO>> searchStaff(
            @Parameter(description = "关键词") @RequestParam(required = false) String keyword,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "物业公司ID数组") @RequestParam(required = false) String propertyCompanyIds) throws Exception {
        log.info("搜索员工，关键词：{}，状态：{}，物业公司ID：{}", keyword, status, propertyCompanyIds);
        
        Long currentUserId = SecurityUtils.getCurrentUserId();
        
        StaffQueryDTO queryDTO = new StaffQueryDTO();
        queryDTO.setKeyword(keyword);
        queryDTO.setStatus(status);
        
        if (propertyCompanyIds != null && !propertyCompanyIds.trim().isEmpty()) {
            String[] ids = propertyCompanyIds.split(",");
            Long[] propertyCompanyIdsArray = new Long[ids.length];
            for (int i = 0; i < ids.length; i++) {
                propertyCompanyIdsArray[i] = Long.parseLong(ids[i].trim());
            }
            queryDTO.setPropertyCompanyIds(propertyCompanyIdsArray);
        }
        
        List<StaffVO> result = staffService.searchStaff(queryDTO, currentUserId);
        
        return Result.success("搜索成功", result);
    }
}